<?php


namespace App\Services\Patent;

use App\Agency;
use App\PatentApply;
use App\Repositories\PatentApplyRepository;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use PhpOffice\PhpWord\TemplateProcessor;

class PatentApplyService
{

    public function downloadTable($model)
    {
        $templateProcessor = $this->tableTemplateProcessor($model);
        $res = $templateProcessor->save();
        $content = file_get_contents($res);
        unlink($res);
        return response_stream_download($content, $model['patent_name'] . '(申请前评估表).docx');;
    }

    public function tableTemplateProcessor($model)
    {
        $is_woman = '☑';
        $is_man = '□';
        //实例化 phpword 类
//        $PHPWord = new PhpWord();
        //指定事先制作好的模板文件路径
        $templateProcessor = new TemplateProcessor(public_path("template/register_table_template.docx"));
        $templateProcessor->setValue('org_name', org_name());
        $data = [
            'patent_name'    => $model['patent_name'],
            'inventor'       => $model['inventor'],
            'charge_person'  => $model['charge_person'],
            'contact_person' => $model['contact_person'],
            'phone'          => $model['phone'],
            'department'     => $model->department->name ?? '',

            'applicant#1'       => !$model['other_applicant'] ? $is_woman : $is_man,
            'applicant#2'       => $model['other_applicant'] ? $is_woman : $is_man,
            'applicant#2#other' => $model['other_applicant'] ?: "\r\r\r\r\r\r\r\r",

            'patent_type#1'        => $model['patent_type_id'] == 1 ? $is_woman : $is_man,
            'patent_type#2'        => $model['patent_type_id'] == 2 ? $is_woman : $is_man,
            'patent_type#3'        => $model['patent_type_id'] == 3 ? $is_woman : $is_man,
            'patent_type#4'        => $model['patent_type_id'] == 4 ? $is_woman : $is_man,
            'patent_type#4#code'   => $model['patent_type_id'] == 4 && $model['other_patent_sn'] ? $model['other_patent_sn'] : "CN\r\r\r\r\r\r\r\r",
            'patent_type#5'        => $model['patent_type_id'] == 5 ? $is_woman : $is_man,
            'patent_type#5#county' => $model['county'] ?: "\r\r\r ",
            'patent_type#5#1'      => $model['apply_channel'] == 1 ? $is_woman : $is_man,
            'patent_type#5#2'      => $model['apply_channel'] == 2 ? $is_woman : $is_man,
            'patent_type#5#code'   => $model['apply_channel'] == 2 && $model['other_patent_sn'] ? $model['other_patent_sn'] : "\r\r\r\r\r",

            'patent_attr'      => $this->getSelectTemplate(PatentApply::PATENT_ATTR, $model['patent_attr']),
            'te_source'        => $this->getSelectTemplate(PatentApply::TE_SOURCE, $model['te_source']),
            'te_source_remark' => $model['te_source_remark'] ?: '',

            'te_field'        => $this->getSelectTemplate(PatentApply::TE_FIELD, $model['te_field']),
            'te_field_remark' => $model['te_field_remark'] ?: "\r\r",

            'te_maturity'        => $this->getSelectTemplate(PatentApply::TE_MATURITY, $model['te_maturity']),
            'te_maturity_remark' => $model['te_maturity_remark'] ?: "\r\r\r",

            'te_innovate' => $this->getSelectTemplate(PatentApply::TE_INNOVATE, $model['te_innovate']),

            'ptm'        => $this->getSelectTemplate(PatentApply::PTM, $model['ptm']),
            'ptm_remark' => $model['ptm_remark'] ?: "\r\r\r\r",

            'novelty'      => $this->getSelectTemplate(PatentApply::NOVELTY, $model['novelty'], "\r\r"),
            'creativity'   => $this->getSelectTemplate(PatentApply::CREATIVITY, $model['creativity'], "\r\r"),
            'practicality' => $this->getSelectTemplate(PatentApply::PRACTICALITY, $model['practicality'], "<w:br/>\r\r\r\r"),
            'prospect'     => $this->getSelectTemplate(PatentApply::PROSPECT, $model['prospect'], "\r\r"),
            'created_at'   => date('Y年m月d日', Carbon::parse($model['created_at'])->getTimestamp()),

            'cts'                => $model['cts'],
            'ownership_divide#1' => $model['ownership_divide'] == 1 ? $is_woman : $is_man,
            'ownership_divide#2' => $model['ownership_divide'] == 2 ? $is_woman : $is_man,

            'dept_review#1' => $model['dept_review_status'] == 1 ? $is_woman : $is_man,
            'dept_review#2' => $model['dept_review_status'] == 2 ? $is_woman : $is_man,

            'dept_review_remark' => $model['dept_review_remark'] ?? "",

            'retrieval_remark'  => $model['retrieval_remark'] ?? '',
            'evaluation_remark' => $model['evaluation_remark'] ?? '',
        ];
        $templateProcessor->setValues($data);
        return $templateProcessor;
    }


    public function getSelectTemplate($data, $select, $empty = "\r")
    {
        $is_woman = '☑';
        $is_man = '□';
        $str = '';
        $end = end($data);
        foreach ($data as $key => $value) {
            $check = $key == $select ? $is_woman : $is_man;
            $str .= $check;
            $str .= $value;
            if ($end != $value) {
                $str .= $empty;
            }
        }
        return $str;
    }

    public function form($model = null)
    {
        $user = Admin::user();
        /** @var  PatentApplyRepository $repository */
        $repository = app(PatentApplyRepository::class);
        $form = $repository->form();
        if ($form->isCreating()) {
            $form->hidden('uuid', __('编号'));
            $form->hidden('serial_number')->default(0);
            $form->hidden('year')->default(date('Y'));
        }
        $form->text('patent_name', __('拟申请专利名称'))->required();
        $form->text('inventor', __('全体发明人'))->required()->default($user->name);
        $form->text('charge_person', __('专利负责人'))->required()->help('第一发明人')->default($user->name);
        $form->text('contact_person', __('联系人'))->required()->default($user->name)->width('150px');
        $form->mobile('phone', __('联系电话'))->required()->default($user->mobile);
        $form->text('patent_person', __('专利权人'))->required()->default(org_name())->help('第一申请人');
        $form->text('other_applicant', __('合作申请单位'))->help('合作申请，其他申请人');
        $form->hidden('applicant');
        $form->radio('patent_type_id', '专利类别')->required()->options(patent_type_select_option())
            ->when(4, function (Form $form) {
                $form->text('other_patent_sn', '国内申请号')->width('200px');
            })->when(5, function (Form $form) {
                $form->text('country', '具体国家')->width('200px');
                $form->radio('apply_channel', '申请途径')->default(0)->options(PatentApply::APPLY_CHANNEL);
                $form->text('other_patent_sn', '申请号')->width('200px');
            });
        if (config('settings.module.expert_module')) {
            $form->radio('patent_attr', '专利属性')->options(PatentApply::PATENT_ATTR)->required();
            $form->radio('te_source', '技术来源')->options(PatentApply::TE_SOURCE)->required();
            $form->text('te_source_remark', '技术来源备注')->placeholder('选择技术来源后，备注课题名称及编号');
            $form->select('te_field', '技术领域')->options(PatentApply::TE_FIELD)->required()
                ->when(11, function (Form $form) {
                    $form->text('te_field_remark', '技术领域(其它)')->width('200px');
                });
            $form->radio('te_maturity', '技术成熟度')->options(PatentApply::TE_MATURITY)->required()
                ->when(count(PatentApply::TE_MATURITY), function (Form $form) {
                    $form->text('te_maturity_remark', '技术成熟度(其它)');
                });
            $form->radio('te_innovate', '技术创新度')->options(PatentApply::TE_INNOVATE)->required();
            $form->select('ptm', '拟采取转化方式')->options(collect(PatentApply::PTM))->when(6, function (Form $form) {
                $form->text('ptm_remark', '拟采取转化方式(备注)');
            })->required();
            $form->divider('专利创新性及可转化性自评');
            $form->radio('novelty', '新颖性')->options(PatentApply::NOVELTY)->required();
            $form->radio('creativity', '创造性')->options(PatentApply::CREATIVITY)->required();
            $form->radio('practicality', '实用性')->options(PatentApply::PRACTICALITY)->required();
            $form->radio('prospect', '应用前景')->options(PatentApply::PROSPECT)->required();
            $form->divider('');
            $form->textarea('cts', '核心技术方案')->placeholder('简述该项专利的核心技术方案并列明该项专利的全部权利要求。')->required();
        }
        $form->file('file', __('技术交底书'))->uniqueName()->hidePreview()->required();
        $form->radio('ownership_divide', '是否所有权分割')->options([1 => '是', 2 => '否'])->default(2)->required();
        $agentColumn = $form->radio('is_agent', '是否走代理')->options(['否', '是'])->required()
            ->when(1, function (Form $form) {
                $form->select('agency_id', '意向代理机构')->options(Agency::selectOptions()->prepend('-----请选择-----', 0));
            })
            ->when(0, function (Form $form) {
                $form->file('retrieval_report', '检索报告')->uniqueName()->hidePreview()->help('上传第三方机构出具的查新检索报告，须明确是否具有专利性');
            });
        if ($form->isCreating()) {
            $agentColumn->default(1);
        }
        Admin::style('label[for="retrieval_report"]:before{content: "* ";color: red;}');
        $script = <<<SCRIPT
     $('.is_agent').on('ifChecked', function (e) {
        var checked = $(this).val();
        if(checked == 1){
           $('div.cascade-group.cascade-is_agent-0 input').removeAttr('required');
        }else{
         $('div.cascade-group.cascade-is_agent-0 input').attr('required',1);
        }
    })
     $('div.cascade-group.cascade-is_agent-0 input').removeAttr('required');
SCRIPT;
        Admin::script($script);
        $form->hidden('review_status');
        $form->hidden('dept_review_status');
        $form->hidden('review_remark');
        $form->hidden('file_time');
        if ($form->isCreating()) {
            $form->hidden('user_id', __('用户ID'));
            $form->hidden('department_id');
        }
        $form->saving(function (Form $form) use ($user,$repository) {
            $input = request()->all();
            unset($input['is_agent']);
            if ($form->isCreating()) {
                $form->user_id = $user->id;
                $form->department_id = $user->department_id;
                $form->year = date('Y');
                $form->serial_number = $repository->getSerialNumber($form->year);
                $form->uuid = $repository->getApplyNewCode($form->year, $form->serial_number);
            }

            if (in_array($user['role_type'], [1, 2])) {
                $form->review_status = 0;
                $form->dept_review_status = 1;
            } else {
                $form->review_status = 0;
                $form->dept_review_status = 0;
            }
            $form->review_remark = '';
            $form->applicant = $form->patent_person;
            if ($form->other_applicant) {
                $form->applicant = $form->patent_person . ',' . $form->other_applicant;
            }
            if ($form->is_agent == 1) {
                $form->agency_id = $form->agency_id ?: 0;
            } else {
                if (!$form->model()->retrieval_report && !$form->retrieval_report) {
                    admin_toastr('不走代理请上传第三方机构出具的查新检索报告', 'error');
                    $data = request()->all();
                    $data['is_agent'] = 1;
                    return back()->withInput($data);
                }
                $form->agency_id = 0;
                $form->is_agent = 0;
            }
            if ($form->file) {
                $form->file_time = Carbon::now();
            }
        });
        $form->saved(function (Form $form) use ($user) {
            $model = $form->model();
            if ($model['review_status'] != 1) {
                if ($form->isCreating()) {
                    $model->remarks()->create([
                        'name'    => '发起申请',
                        'user_id' => $user['id'],
                        'remark'  => '',
                    ]);
                } else {
                    $model->remarks()->create([
                        'name'    => '修改申请',
                        'user_id' => $user['id'],
                        'remark'  => '',
                    ]);
                }
            }
        });
        return $form;
    }

}
